package com.sen.common.security.jcaptcha;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

import com.octo.captcha.service.CaptchaService;
import com.octo.captcha.service.CaptchaServiceException;

/**
 * 基于JCaptcha的验证器.
 * 
 * @author sen
 */
public final class JCaptchaValidator {
	private static Logger log = Logger.getLogger(JCaptchaValidator.class);
	
	private CaptchaService captchaService;
	private HttpServletRequest request;

	public JCaptchaValidator(CaptchaService captchaService,
			HttpServletRequest request) {
		this.captchaService = captchaService;
		this.request = request;
	}

	/**
	 * 验证验证码.
	 * 
	 * @param userCaptchaResponse
	 *            用户输入的验证码.
	 * @return 若和生成的验证码一致, 则返回true, 否则返回false.
	 */
	public boolean validate(String userCaptchaResponse) {
		if (request.getSession(false) == null) {
			return false;
		}
		try {
			String captchaID = request.getSession().getId();

			return captchaService.validateResponseForID(captchaID, userCaptchaResponse);
		} catch (CaptchaServiceException e) {
			log.error(e.getMessage(), e);
			return false;
		}
	}
}
